package org.fatewa.engine.utils;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.fatewa.engine.genius.base.Operator;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 4everlynn
 */
@Slf4j
public class Qs {
    private static final Pattern QUERY_REGEXP = Pattern.compile("(\\w+)\\[(.+?)]=*(.*)");

    private static final Map<String, String> OPS_MAPPER = new HashMap<>();


    static {
        OPS_MAPPER.put("eq", "equals");
        OPS_MAPPER.put("like", "like");
        OPS_MAPPER.put("btw", "between");
        OPS_MAPPER.put("lt", "lessThan");
        OPS_MAPPER.put("le", "lessEquals");
        OPS_MAPPER.put("gt", "greatThan");
        OPS_MAPPER.put("ge", "greatEquals");
    }

    /**
     * 解析出参数的操作集合
     *
     * @param request HttpServletRequest 请求
     * @return 以字段名称为Key 的操作对象
     */
    public static Map<String, Operator> parse(HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();

        Map<String, Operator> result = new HashMap<>(30);

        for (String param : parameterMap.keySet()) {
            Matcher matcher = QUERY_REGEXP.matcher(param);
            if (matcher.find()) {
                // 当前字段
                String field = matcher.group(1);
                // 当前的查询操作
                String operator = matcher.group(2);
                // 查询操作对应 Operator 的字段名称
                String operatorField = OPS_MAPPER.get(operator);

                // 不在已知的操作字段列中，则跳过
                if (Strings.isEmpty(operatorField)) {
                    continue;
                }

                // 用户输入的查询值
                String value = matcher.group(3);

                if (Strings.isEmpty(value)) {
                    // 不在key中时，从值中获取
                    String[] values = parameterMap.get(param);
                    if (values.length > 0) {
                        // 当同一个参数传入多次时，使用最后一个值
                        value = values[values.length - 1];
                    } else {
                        // 查询值为空，跳过
                        continue;
                    }
                }

                try {
                    Operator operators = new Operator();
                    // 可操作字段
                    Field declaredOperatorField = Operator.class.getDeclaredField(operatorField);
                    declaredOperatorField.setAccessible(true);
                    declaredOperatorField.set(operators, value);

                    // 确保初始值存在
                    result.putIfAbsent(field, new Operator());

                    Operator currentField = result.get(field);

                    declaredOperatorField.set(currentField, value);
                    declaredOperatorField.setAccessible(false);

                    // 更新值
                    result.put(field, currentField);
                } catch (NoSuchFieldException e) {
                    log.warn("Field {} not exists in Type {}", operatorField, Operator.class);
                } catch (IllegalAccessException e) {
                    log.warn("");
                }


            }
        }

        return result;
    }

}
